import axios from "axios";
import { getAdminToken, removeAdminToken } from "@/utils/auth";
import { Message } from "element-ui";
import router from "@/router";
import errorCode from "@/utils/errorCode";


const requestV2 = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: "/api",
  // 超时
  timeout: 60000,
  // 禁用 Cookie 等信息
  withCredentials: false,
  headers: {
    "Content-Type": "application/json;charset=utf-8"
  }
});

/**
 * 请求拦截
 * */
requestV2.interceptors.request.use(
  config => {
    let adminToken = getAdminToken();
    if (adminToken) {
      config.headers.Authorization = adminToken;
    }
    // get请求映射params参数
    if (config.method === "get" && config.params) {
      let url = config.url + "?";
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName];
        const part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof (value) !== "undefined") {
          if (typeof value === "object") {
            for (const key of Object.keys(value)) {
              let params = propName + "[" + key + "]";
              const subPart = encodeURIComponent(params) + "=";
              url += subPart + encodeURIComponent(value[key]) + "&";
            }
          } else {
            url += part + encodeURIComponent(value) + "&";
          }
        }
      }
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

// 响应拦截器
requestV2.interceptors.response.use(
  async res => {
    let resData;
    if (res.config.responseType === "blob") {
      await parseBlob(res).then(r => {
        resData = r;
      });
    } else {
      resData = res.data;
    }
    // 未设置状态码则默认成功状态
    const code = resData.code || 0;
    if (code === 0) {
      return resData.result;
    }
    // 获取错误信息
    const msg = resData.result || errorCode[code] || errorCode["default"];
    if (code === 401) {
      // 401 清除token信息并跳转到登录页面
      removeAdminToken();
      // 只有在当前路由不是登录页面才跳转
      router.currentRoute.path !== "/login" &&
      await router.replace({
        path: "/login",
        query: { redirect: router.currentRoute.path }
      });
    } else if (code === 500) {
      Message({
        message: msg,
        type: "error"
      });
    } else if (code === 501) {
      Message({
        type: "error",
        duration: 0,
        message: msg
      });
    }
    Message({
      message: msg,
      type: "error",
      duration: 3 * 1000
    });
    return Promise.reject(new Error(msg));
  },
  err => {
    console.log("err" + err);
    let { message } = err;
    if (message === "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: "error",
      duration: 3 * 1000
    });
    return Promise.reject(err);
  });

function parseBlob(res) {
  return new Promise((resolve, reject) => {
    if (res.data.type === "application/json") {
      let reader = new FileReader();
      reader.onload = function(event) {
        try {
          const parsedData = JSON.parse(event.target.result);
          resolve(parsedData);
        } catch (error) {
          reject(error);
        }
      };
      reader.readAsText(res.data);
    } else if (res.data.type === "application/octet-stream") {
      let fileName = undefined;
      let contentDisposition = res.headers["content-disposition"];
      if (contentDisposition) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(contentDisposition);
        if (matches != null && matches[1]) {
          fileName = decodeURIComponent(matches[1].replace(/['"]/g, ""));
        }
      }
      resolve({
        code: 0,
        message: "解析成功",
        result: {
          bold: res.data,
          fileName: fileName
        }
      });
    } else {
      reject(new Error(`解析 Blob 失败 暂不支持的类型 : ${res.data.type}`));
    }
  });
}


export default requestV2;